package com.eshore.web.controller;

import com.eshore.demo.qingjia.service.ILzyQingjiaApplyFormService;
import com.eshore.khala.common.annotation.LoginUser;
import com.eshore.khala.common.model.SysUser;
import com.eshore.khala.core.starter.common.Result;
import com.eshore.khala.core.starter.web.controller.BaseController;
import com.eshore.web.vo.DemoUnitTest001FlowDTO;
import com.eshore.workflow.service.TaskInstanceIdentity;
import com.eshore.workflow.service.WorkflowService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * REST controller for managing 页面DemoUnitTest001相关的工作流.
 *
 * @author ctsi-biyi-generator
 *
 */
@RestController
@RequestMapping("/api/DemoUnitTest001")
public class DemoUnitTest001FlowController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(DemoUnitTest001FlowController.class);

    private WorkflowService     workflowService;

    private final ILzyQingjiaApplyFormService   service;

    public DemoUnitTest001FlowController(ILzyQingjiaApplyFormService lzyQingjiaApplyFormService,
                                WorkflowService workflowService) {
        this.service = lzyQingjiaApplyFormService;
        this.workflowService = workflowService;
    }

    @InitBinder   
    public void initBinder(WebDataBinder binder) {   
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @PostMapping("/flowSubmit")
    public Result<String>
    submitWorkflow(@RequestBody DemoUnitTest001FlowDTO requestDto, @LoginUser SysUser user) {
        String userIdentity = String.valueOf(user.getId());
        TaskInstanceIdentity taskInstanceIdentity = findTaskInstanceIdentity(requestDto, userIdentity);

        if (taskInstanceIdentity != null) {
            // 【工作流触发】：触发任务完成

            // 业务数据入库
            String bizKey = insertOrUpdateBziData(requestDto);

            // 按需添加自定义逻辑：完成任务前的逻辑

            Map<String, Object> extraParams = collectRelatedExtraParamsForSubmit(requestDto);
            //TODO 按流程定义需要填充参数

            // 或按需替换为业务需要的工作流触发逻辑
            workflowService.completeTask(taskInstanceIdentity.getTaskInstanceId(), extraParams);

            // 按需添加自定义逻辑：完成任务后的逻辑

            return Result.success(bizKey);
        }

        String flowKey = requestDto.get_flowKey();
        if (StringUtils.isNotEmpty(flowKey)) {
            // 【工作流触发】：启动流程

            // 业务数据入库
            String bizKey = insertOrUpdateBziData(requestDto);

            // 按需添加自定义逻辑：启动流程前的逻辑

            Map<String, Object> extraParams = collectRelatedExtraParamsForSubmit(requestDto);
            //TODO 按流程定义需要填充参数

            // 或按需替换为业务需要的工作流触发逻辑
            workflowService.startProcess(flowKey, userIdentity, bizKey, extraParams);

            // 按需添加自定义逻辑：启动流程后的逻辑
        }

        return Result.failed("流程相关参数不全或对应的流程不存在");
    }

    /**
    *  收集流程流转需要的附加参数，需要参考流程当前环节的定义
    */
    private Map<String, Object> collectRelatedExtraParamsForSubmit(DemoUnitTest001FlowDTO requestDto) {
        Map<String, Object> extraParams = new HashMap<>();

        extraParams.put("flowResult", requestDto.getApprovaRstCode());
        extraParams.put("flowNext", requestDto.get_flowNext());
        extraParams.put("flowPeople", requestDto.getFlowNextHandler());

        return extraParams;
    }


    @PostMapping("/flowWithdraw")
    public Result<String>
    withdrawWorkflow(@RequestBody DemoUnitTest001FlowDTO requestDto, @LoginUser SysUser user) {
        String userIdentity = String.valueOf(user.getId());
        TaskInstanceIdentity taskInstanceIdentity = findTaskInstanceIdentity(requestDto, userIdentity);

        if (taskInstanceIdentity == null) {
            return Result.failed("流程相关参数不全或对应的流程不存在");
        }

        // 按需添加自定义逻辑

        Map<String, Object> extraParams = new HashMap<>();
        // 按流程定义需要填充参数

        Result<Boolean> wfRst = workflowService.backToPreviousStep(taskInstanceIdentity.getProcessInstanceId(), taskInstanceIdentity.getTaskInstanceId());
            if (wfRst == null || !wfRst.getResult()) {
            return Result.failed(String.format("流程触发不成功：%s", (wfRst != null ? wfRst.getMsg() : "未知")));
        }

        // Step2: 业务数据入库
        String bizKey = insertOrUpdateBziData(requestDto);

        return Result.success(bizKey);
    }


    private TaskInstanceIdentity
    findTaskInstanceIdentity(DemoUnitTest001FlowDTO requestDto, String userId) {
        String flowTaskKey = requestDto.get_flowTaskKey();
        String flowTaskId = requestDto.get_flowTaskId();
        String flowKey = requestDto.get_flowKey();
        String flowId = requestDto.get_flowId();

        if (StringUtils.isNotEmpty(flowTaskId)) {
            return workflowService.findTaskInstanceIdentity(flowTaskId);
        }
        if (StringUtils.isNotEmpty(flowId) && StringUtils.isNotEmpty(flowTaskKey)) {
            return workflowService.findTaskInstanceIdentity(flowId, flowTaskKey);
        }
        if (StringUtils.isNotEmpty(flowKey) && StringUtils.isNotEmpty(flowTaskKey)
            && requestDto.getId() != null) {
            String bizKey = String.valueOf(requestDto.getId());
            return workflowService.findTaskInstanceIdentity(flowKey, flowTaskId, bizKey, userId);
        }

        return null;
    }

    /**
     * 保存业务数据
     */
    private String insertOrUpdateBziData(DemoUnitTest001FlowDTO requestDto) {
        service.saveOrUpdate(requestDto);
        return String.valueOf(requestDto.getId());
    }

}